use warnings;
use strict;

sub WatchList {
	my ($return, $return_link) = @_;
	unless (-e "$VAR{'WatchFile'}"){
		open (WTXT, ">$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (100)", 1, 1);
		print WTXT "### TV\n";
		print WTXT "### VIDEO\n";
		close WTXT or warn $!;
	}
	print "Content-type: text/html\n\n";
	$VAR{'HaveHeader'} = 1;
	my $related_links = &HtmRelated ('Watch List', '', $return);
	my $vid = 0;
	print &HtmHead ('Watch List', "<P>The easiest way to add Watch List entries is from a browse page.<br>All nzb listings have a \"Add to Watch List\" link.<br>Clicking 'Add...' will add the entry and return you to the browse page.<br>Click the 'return to' (browse page) link if you change your mind.</P><B class=\"INFO\"><A NAME=\"TV\">TV</A></B>&nbsp;&nbsp;&nbsp;Go to: <A HREF=\"#VIDEO\">Video</A>&nbsp;&nbsp;&nbsp;<A HREF=\"#top\">top</A><pre><font face=\"Monospace,Courier,Courier New\">", $return_link, $return, $related_links);
	open(RTXT, "$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (101)", 1, 1);
	while (<RTXT>) {
		chomp;
		if (m!^#\w!){
			next;
		}
		elsif (m!^### (.+)!){
			if ($1 eq 'VIDEO'){
				$vid = 1;
				print "</font></pre>\n";
				&PrintShowForm ('Add', '', '', '', '', '', '');
				print '<br><br><B class="INFO"><A NAME="VIDEO">Video</A></B>&nbsp;&nbsp;&nbsp;Go to: <A HREF="#TV">TV</A>&nbsp;&nbsp;&nbsp;<A HREF="#top">top</A><pre><font face="Monospace,Courier,Courier New">';
				printf "\ndel edt   %-60s\t yr\t res\t pri\t save name\n", "Video title";
				printf "--- ---   %-60s\t ---\t ---\t ---\t ----------\n", "----------"; 
			}
			else { 
				printf "del edt   %-60s\t ep\t res\t pri\t save name\n", "Show title"; 
				printf "--- ---   %-60s\t ---\t ---\t ---\t ----------\n", "----------"; 
			}
		}
		elsif (m!^([^\t]+)\t([^\t]*)\t([^\t]+)\t(([^\t]+)\t)?(.*)$!){ # title, ep, res, pr, save
			my $label = '';
			my $save_name = '';
			my $st = '';
			my $priority = '   ';
			my $title = $1;
			if ($2){ $label = $2; }
			my $res = $3;
			if ($4){ $priority = $5; }
			if ($6 and !$vid){ 
				$save_name = $6;
				if ($save_name ne $title){
					$st = $save_name;
				}
				$save_name =~ s!^# !!;
				$save_name = "<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$save_name&amp;ep=&amp;id=&amp;db=&amp;re=TV\">$save_name</a>";
			}
			elsif ($6 and $title ne $6){ # only print $save_name if its different
				$save_name = $6;
				$st = $6;
			}
			my $nt_enc = $title;
			$nt_enc =~ s!\s+$!!;
			$nt_enc =~ s!^#!HASH!g;
			$nt_enc =~ s!^([^,]+),.+!$1!; # first name only for delete link
			#$nt_enc =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg; # messes up printf - how to do?
			my $type;
			if ($vid){ $type = 'VD'; }
			else { $type = 'TV'; }
# 			if ($ep_res =~ m!.+\t!){ $type = 'TV'; }
# 			else { $type = 'VIDEO'; }
			#$res =~ s!HD\+!HD%2B!;
# 			my $enc_res = $res;
# 			$enc_res =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg;
			printf "<A HREF=\"$VAR{'WfCgi'}?do=WL_Delete_form&amp;nt=$nt_enc&amp;la=$label&amp;re=$res&amp;ca=$type\"> x</A>  <A HREF=\"$VAR{'WfCgi'}?do=WL_Edit_form&amp;nt=$nt_enc&amp;la=$label&amp;re=$res&amp;ca=$type\"> e</A>    %-60s\t $label\t $res\t $priority\t $save_name\n", $title;
		}
	}
	close RTXT or warn $!; #</tt>
	print "</font></pre>\n";
	&PrintMovieForm ('Add', '', '', '', '', '', '');
	my $menu = &HtmlMenu;
	print &HtmFoot ($return_link, $return, '');
}

sub WatchEdit {
	my ($do, $title, $label, $res, $ca) = @_; # only up to res for type
	# $title =~ s!%20! !g;
	$title =~ s!%([a-fA-F0-9]{2,2})!chr(hex($1))!eg;
	$title =~ s!^HASH !# !; # should see if not having the above motivated this hack
	unless ($label){ $label = 100; }
	
	print "Content-type: text/html\n\n";
	$VAR{'HaveHeader'} = 1;
	my $related_links = &HtmRelated ("$do watch list entry", '');
	print &HtmHead ("$do watch list entry", '', "$VAR{'WfCgi'}?watchlist", 'Return to Watch List', $related_links);
	open (RTXT, "<$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (122)", 1, 1);
	while (<RTXT>){ # use a single form call with empty ep?... would need to add desc line variables
		chomp;
		# TV  $type, $title, $label, $res, $priority, $save_title, $return
		#if (m!^(\Q$title\E[^\t]*)\t([^\t]+)\t(?:DD|SR|HR|SX|SA|H7|H1|HS|AT)\t(([^\t]+)\t)?(.*)$!i){ 
		if ($ca eq 'TV' and m!^(\Q$title\E[^\t]*)\t$label\t$res\t(([^\t]+)\t)?(.*)$!i){ 
			#if ($3){ &PrintShowForm ($do, $1, $2, $res, $3, $4, ''); }# $type, $title, $ep_yr, $res, $priority, $save, ''
			#else { &PrintShowForm ($do, $1, $2, $res, '', $4, ''); } # $type, $title, $ep_yr, $res, '', $save, ''
			&PrintShowForm ($do, $1, $label, $res, $3, $4, ''); # $type, $title, $yr, $res, $priority, $save
			last;
		}
		# vid
		elsif ($ca eq 'VD' and m!^(\Q$title\E[^\t]*)\t([^\t]*)\t$res\t(([^\t]+)\t)?(.*)$!i){ 
			#if ($3){ &PrintMovieForm ($do, $1, $2, $res, $3, $4, ''); }
			#else { &PrintMovieForm ($do, $1, $2, $res, '', $4, ''); }
			&PrintMovieForm ($do, $1, $2, $res, $4, $5, ''); # $type, $title, $yr, $res, $priority, $save
			last;
		}
# 		# year format
# 		elsif (m!^($title[^\t]*)\t\t([^\t]+)\t([^\t]+)$!i){ # 3 tabs here VS 2 below
# 			&PrintMovieForm ($do, $1, '', $2, $3, ''); #$type, $title, $ep, $res, $save
# 			last;
# 		}
# 		# old format
# 		elsif (m!^($title[^\t]*)\t([^\t]+)\t([^\t]+)$!i){
# 			#              $type, $old_title, $res, $save_title, $return
# 			&PrintMovieForm ($do, $1, '', $2, $3, ''); #$type, $title, $res, $save
# 			last;
# 		}
	}
	close RTXT or warn $!;
	print &HtmFoot ("$VAR{'WfCgi'}?watchlist", 'Return to Watch List', '');
}

sub WatchSave {
	#my (%var) = @_; # do, nt, ep, res, st, ca, sc, ot, pr<new
	my ($cgi) = @_;
	# new_title, episode, resolution, (nzb)site_title, (local)cat, (nzb)site_cat, old_title
	my $do = $cgi->param('do');
	$do =~ s!^WL_!!; # Add or Edit
	
	my $orig_title = $cgi->param('ot');
	my $new_title = $cgi->param('nt');
	my $save_title = $cgi->param('st');
	unless ($save_title){ # save title
		$save_title = $cgi->param('nt');
		$save_title =~ s!^([^,]+),.+!$1!; # first
		#$save_title =~ s!.+([^,]+)$!$1!; # last
	}

	my $cat = $cgi->param('ca'); # always? sent - is always VD or TV
	
	my $label = $cgi->param('la');
	unless ($label or $cat eq 'VD'){ 
		$label = '100'; 
	}

	my $res = $cgi->param('re');
	unless ($res){
		if ($cat eq 'VD'){
			if ($VAR{'VidNzbs'}){
				$res = $VAR{'VidNzbs'};
			}
			else { $res = 'SR'; }
		}
		elsif ($cat eq 'TV'){
			if ($VAR{'TVNzbs'}){
				$res = $VAR{'TvNzbs'};
			}
			else { $res = 'DR'; }
		}
	}
	
	my $priority = $cgi->param('pr');
	unless ($priority){ $priority = 'norm'; }
	
	my $a_name; # site cat
	my $site_cat = $cgi->param('sc');
	if ($site_cat and $site_cat =~ s!:(\d+)$!!){
		$a_name = $1;
	}
	
	# delete old entry before adding edited/new entry
	if ($do eq 'Edit'){ 
		open (WTXT, ">$VAR{'WatchFile'}.tmp") or &Print ("  Couldn't open $VAR{'WatchFile'}.tmp, $! (123)", 1, 1);
		open (RTXT, "<$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (124)", 1, 1);
		while (<RTXT>){
			#if (m!^$orig_title\t[^\t]+\t$cgi->param{'res'}!i){ # old title
			# ### need more old stuff to prevent deleting multiple entries $cat
			if (m!^\Q$orig_title\E\t$label\t!i){ # old title
				next;
			}
			else { print WTXT; }
		}
		close WTXT or warn $!;
		rename ("$VAR{'WatchFile'}.tmp", "$VAR{'WatchFile'}") or &Print ("  Couldn't rename $VAR{'WatchFile'}.tmp, $! (124)", 1, 1);
		close RTXT or warn $!;
	}
	
	# fill @watch... and check for 'Add' dupe in the process
	my @watch;
	my $grab = 0;
	my $found = 0;
	open(RTXT, "$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (125)", 1, 1);
	while (<RTXT>) {
		if (m!^# ! or m!^[\n\r]!){
			next;
		}
		#elsif (m!^$new_title\t[^\t]+\t$res!i){ # new title
		# ### need more old stuff to prevent deleting multiple entries $cat... and to allow s0n entries
		elsif (m!^\Q$new_title\E\t$label\t!i){ # new title
			$found = 1; 
			last;
		}
		elsif (m!^### VIDEO! and $grab and $cat eq 'TV'){ # if cat = TV stop when reach VIDEO
			last;
		}
		elsif (m!^### $cat!){ # if cat add new entry and grab until end or reach VIDEO (above)
			$grab = 1;
			if ($label){#$cat eq 'TV'){
				push (@watch, "$new_title\t$label\t".$res."\t$priority\t$save_title\n");
			}
			else { push (@watch, "$new_title\t\t".$res."\t$priority\t$save_title\n"); }
		}
		elsif ($grab){
			# ### temporary fix for watch lists w/o year field... added one for lists without priority field
			#my $line = $_;
			#if ($line =~ m!^[^\t]+\t[^\t]*\t[^\t]*\t[^\t]*$!){
			#	$line =~ s!^([^\t]+)\t!$1\t\t!;
			#}
			push (@watch, $_);
		}
	}
	close RTXT or warn $!;
	
	if ($found){
		&Print ("  Watch list already has:$new_title $label (FN66)", 2, 0);
		if ($site_cat){
			#print "Location: $VAR{'Protocol'}$VAR{'Host'}$VAR{'HtmlUrl'}/$site_cat.html#$a_name\n\n";
			print $cgi->redirect($VAR{'Protocol'}.$VAR{'Host'}.$VAR{'HtmlUrl'}.'/'.$site_cat.'.html#'.$a_name);
		}
		else {
			#print "Location: $VAR{'Protocol'}$VAR{'Host'}$VAR{'WfCgi'}?watchlist#$cat\n\n";
			print $cgi->redirect($VAR{'Protocol'}.$VAR{'Host'}.$VAR{'WfCgi'}.'?watchlist#'.$cat);
		}
		exit;
	}
	else {
		$grab = 0;
		my $num = @watch;
		open (WTXT, ">$VAR{'WatchFile'}.tmp") or &Print ("  Couldn't open $VAR{'WatchFile'}.tmp, $! (126)", 1, 1);
		open (RTXT, "<$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (127)", 1, 1);
		while (<RTXT>){
			if (m!^\w! and $grab){
				if (@watch){ #... looks like we're replacing the TV or VIDEO section only
					foreach (sort { lc($a) cmp lc($b) } @watch) { 
						print WTXT; 
					}
					@watch = ();
				}
				else { next; }
			}
			elsif (m!^### $cat! and @watch){
				$grab = 1;
				print WTXT;
				if ($num == 1){ # first entry - no print on sort
					print WTXT @watch;
				}
			}
			elsif (m!^### ! and $grab){ # end of TV rewrite - so movies will print
				$grab = 0;
				print WTXT;
			}
			else { print WTXT; }
		}
		close WTXT or warn $!;
		rename ("$VAR{'WatchFile'}.tmp", "$VAR{'WatchFile'}") or &Print ("  Couldn't rename $VAR{'WatchFile'}.tmp, $! (127)", 1, 1);
		close RTXT or warn $!;
		#chmod (oct($VAR{'Perms'}), "$VAR{'WatchFile'}");
		
		# highlight browse entry
		if ($a_name){
			open (WHTM, ">$VAR{'HtmlDir'}/$site_cat.html.tmp") or &Print ("  Couldn't open $site_cat.html.tmp, $! (128)", 1, 1);
			open (RHTM, "<$VAR{'HtmlDir'}/$site_cat.html") or &Print ("  Couldn't open $site_cat.html, $! (129)", 1, 1);
			while (<RHTM>){
				s!^(<P><A NAME="$a_name".+)<a href="[^"]+">Add to Watch List</a>!$1<B class="DEBUG">On watch list</B>!i;
				print WHTM;
			}
			close WHTM or warn $!;
			rename ("$VAR{'HtmlDir'}/$site_cat.html.tmp", "$VAR{'HtmlDir'}/$site_cat.html") or &Print ("  Couldn't rename $site_cat.html.tmp, $! (129)", 1, 1);
			close RHTM or warn $!;
		}
		# TODO check for tvdb file, do a lookup and fetch if one doesn't exist
		
		if ($cgi->param('db_value') and $cgi->param('db_add')){
			open (WDB, ">>$VAR{'DbFile'}") or &Print ("  Couldn't open $VAR{'DbFile'}, $! (102)", 1, 1);
				print WDB $new_title.' '.$cgi->param('db_value')."\t".'seen'."\t\t\n";
			close WDB or warn $!;
		}
		
		&Print ("WL $do: $save_title (FN83)", 3, 0);
		
		if ($site_cat){
			#print "Location: $VAR{'Protocol'}$VAR{'Host'}$VAR{'HtmlUrl'}/$site_cat.html#$a_name\n\n";
			print $cgi->redirect($VAR{'Protocol'}.$VAR{'Host'}.$VAR{'HtmlUrl'}.'/'.$site_cat.'.html#'.$a_name);
		}
		else { 
			#print "Location: $VAR{'Protocol'}$VAR{'Host'}$VAR{'WfCgi'}?watchlist#$cat\n\n";
			print $cgi->redirect($VAR{'Protocol'}.$VAR{'Host'}.$VAR{'WfCgi'}.'?watchlist#'.$cat);
		}
	}
}

sub WatchDelete {
	#my ($title, $label, $res, $cat) = @_;
	my ($cgi) = @_; #$cgi->param('nt'), $cgi->param('la'), $cgi->param('re'), $cgi->param('ca')
	
	my $title = $cgi->param('nt');
	$title =~ s!%([a-fA-F0-9]{2,2})!chr(hex($1))!eg;
	$title =~ s!^HASH !# !; # should see if not having the above motivated this hack
	my $label = $cgi->param('la');
	my $res = $cgi->param('re');
	open (WTXT, ">$VAR{'WatchFile'}.tmp") or &Print ("  Couldn't open $VAR{'WatchFile'}.tmp, $! (130)", 1, 1);
	open (RTXT, "<$VAR{'WatchFile'}") or &Print ("  Couldn't open $VAR{'WatchFile'}, $! (131)", 1, 1);
	while (<RTXT>){
		if (m!^\Q$title\E[^\t]*\t$label\t$res!i){
			next;
		}
		else { print WTXT; }
	}
	close WTXT or warn $!;
	rename ("$VAR{'WatchFile'}.tmp", "$VAR{'WatchFile'}") or &Print ("  Couldn't rename $VAR{'WatchFile'}.tmp, $! (132)", 1, 1);
	close RTXT or warn $!;
	&Print ("WL Delete: $title (FN35)", 4, 0);
	#print "Location: $VAR{'Protocol'}$VAR{'Host'}$VAR{'WfCgi'}?watchlist#$cat\n\n";
	print $cgi->redirect($VAR{'Protocol'}.$VAR{'Host'}.$VAR{'WfCgi'}.'?watchlist#'.$cgi->param('ca'));
}

sub WatchAdd { #nt la ca sc
	my ($site, $new_title, $label, $cat, $site_cat) = @_;
	my $a_name;
	$site_cat =~ s!:(\d+)$!!;
	$a_name = $1;
	my $enc_title = $new_title;
	$new_title =~ s!%([a-fA-F0-9]{2,2})!chr(hex($1))!eg;
	
	print "Content-type: text/html\n\n";
	$VAR{'HaveHeader'} = 1;
	my $related_links = &HtmRelated ('Add to watch list', '');
	print &HtmHead ('Add to watch list', '', "$VAR{'HtmlUrl'}/$site_cat.html#$a_name", "Return to $site_cat", $related_links);
	if ($cat eq 'VD'){ # get string has VD so this is OK as is
		if ($label){
			&PrintMovieForm ('Add', $new_title, $label, '', '', '', "$site_cat:$a_name");
		}
		else { &PrintMovieForm ('Add', $new_title, '', '', '', '', "$site_cat:$a_name"); }
	}
	elsif ($cat eq 'TV'){
# 		if ($VAR{'EpTitle'} and !-e "$VAR{'PPWebDir'}/data/tvdb/$new_title.txt"){
# 			print qq~<P>Note: Episode title lookups will be faster with an episode list.<br>
# 			Clicking the listing TVDb ep link after adding $new_title to your watch list will create one.</P>~;
# 			#You can also [ <a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$enc_title&amp;ep=$label&amp;id=&amp;db=&amp;re=$site_cat:$a_name\">create one now</a> ].
# 		}
		if ($label){
			&PrintShowForm ('Add', $new_title, $label, '', '', '', "$site_cat:$a_name");
		}
		else { &PrintShowForm ('Add', $new_title, '', '', '', '', "$site_cat:$a_name");
	}
	print &HtmFoot ("$VAR{'HtmlUrl'}/$site_cat.html#$a_name", "Return to $site_cat", ''); }
}

sub PrintShowForm { # $type, $title, $yr, $res, $priority, $save
	# from listing example: nt=The%20Apprentice&la=1203&ca=TV&sc=Nzbsrus_TV-x264:2
	my ($type, $title, $label, $res, $priority, $save_title, $return) = @_ ;
	my $select;
	my $cat;
	my $s;
	my $e;
	if ($label =~ m!s0?(\d+)e(\d+)!){
		$s = $1;
		$e = $2;
		$label = $1.$2;
	}
# 	if ($return =~ m!TV-([^:]+):!){ #Nzbsrus_TV-x264:2
# 		$select = $1;
# 		$cat = "TV-$1";
# 		$select =~ s!SR!SD!;
# 		$select =~ s!XviD!SD!i;
# 		$select =~ s!x264!SX!i;
# 		$select =~ s!HR!HD!;
# 	}
	#my $hd_plus = 'HD+';
	#$hd_plus =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg;
	print qq~
	<form action="$VAR{'WfCgi'}" method="$VAR{'FormMethod'}">
	<INPUT TYPE="hidden" NAME="do" VALUE="WL_$type">
	<P><B class="INFO">Show&nbsp;title</B> - can be a comma seperated list of EpGuides, IMDb, AKA, etc. titles<br>
	Listing titles are not always consistent, include any variations you notice on nzb site browse pages.<br>
	Note: The first listed title needs to be the full/punctuated title for [<A HREF="http://epguides.com/">EpGuides</A>] ep title lookups to work 100%.<br>
	Note: TVDb ep title lookups use the PPWeb listing title, but require at least one manual show or ep lookup to work.<br>
	Use listing links, or click the titles in the save name column on the watch list page, to fetch/view the TVDb show record.<br>
	<INPUT TYPE="text" SIZE="60" NAME="nt" value="$title">
	</P>
	
	<P>Last episode - (n)nnn format, one or two digit season and two digit episode. empty/blank = 100<br>
	All future episodes with be fetched. Note: any reposts of current season eps will be fetched if they're not in the db.<br>
	Date based shows rely on the database and any episodes not in the databse will be fetched (Last episode is ignored).<br>
	To watch for nzbs containing a full season of episodes, use the special sNN (e.g. s03) flag instead of an ep number.<br>
	~;
	if ($label){ 
		print "<INPUT TYPE=\"text\" SIZE=\"10\" NAME=\"la\" value=\"$label\"></P>\n\n"; 
	}
	else { print "<INPUT TYPE=\"text\" SIZE=\"10\" NAME=\"la\" value=\"\"></P>\n\n"; }

	
	if ($s and $e and $s >= 1 and $e - 1 > 1){
		my $pre = $e - 1;
		$pre =~ s!^\d$!0$pre!;
		print "<P>Mark previous episodes as seen to prevent re downloading.<br>";
		print '<INPUT TYPE="text" SIZE="10" NAME="db_value" value="'.$s.'01-'.$pre.'">
		<INPUT TYPE=radio NAME="db_add" VALUE="1" CHECKED>yes
		<INPUT TYPE=radio NAME="db_add" VALUE="0">no</P>'."\n\n"; 
	}#TYPE=checkbox NAME="send_receipt" VALUE="yes" CHECKED <INPUT TYPE=radio NAME="db_add" VALUE="yes" CHECKED><INPUT TYPE=radio NAME="db_add" VALUE="no">
	
	if ($select){ print "	<P>Which category to watch (currently $cat):<br>\n"; }
	else { print "	<P>Which quality level or category(s) to watch:<br>\n"; }
	#print "	<P>Which category to watch (enabled for one or more sites):<br>\n";
# 	print "	SR = Standard Resolution - SD, XviD and (SD-)x264 categories (x264, XviD and unlabeled)<br>\n";
# 	print "	SX = SR x264 matches only - any category (not > 480p)<br>\n";
# 	print "	H7 = 720[px] matches only - any category<br>\n";
# 	print "	HR = High Resolution - HD, H264, HD-x264, 720p and 1080p categories (x264)<br>\n";
# 	print "	HS = High and Standard, watch all enabled TV categories for new episodes<br>\n";
# 	print "	AT = AnyThing matching title will be downloaded if it isn't in the database (new or old, Last ep ignored)<br>\n";
	#print "	<SELECT NAME=re><OPTION>SR</OPTION><OPTION>SX</OPTION><OPTION>HR</OPTION><OPTION>HS</OPTION><OPTION>AT</OPTION>\n";
	#print "	Note: SR/HR have been depreciated (will be removed eventually) in favor of SD/HD (r151)<br>\n";
	#print "	<SELECT NAME=re><OPTION>SR</OPTION><OPTION>SX</OPTION><OPTION>H7</OPTION><OPTION>HR</OPTION><OPTION>HS</OPTION><OPTION>AT</OPTION>\n";

	unless ($res){
		$res = $VAR{'TvRes'};
		unless ($res){
			$res = 'SR'; 
		}
	}
	
	if ($res eq 'HR'){ print '<INPUT TYPE=radio NAME="re" VALUE="HR" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="HR">'; }
	print 'HR categories - HD, H264, HD-x264, 720p and 1080p (any type; [hx]264, MPEG2 etc.)<br>'."\n";

	if ($res eq 'SR'){ print '<INPUT TYPE=radio NAME="re" VALUE="SR" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="SR">' }
	print 'SR categories - SD, XviD and (SD-)x264 (any type; xvid, x264, etc.)<br>'."\n";

	if ($res eq 'SA'){ print '<INPUT TYPE=radio NAME="re" VALUE="SA" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="SA">'; }
	print 'SA: SD avi/XviD, DVD and BluRay rips only - any enabled category<br>'."\n";

	if ($res eq 'SX'){ print '<INPUT TYPE=radio NAME="re" VALUE="SX" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="SX">'; }
	print 'SX: SD x264/mp4 matches only - any enabled category (not > 480p)<br>'."\n";

	if ($res eq 'H7'){ print '<INPUT TYPE=radio NAME="re" VALUE="H7" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="H7">'; }
	print 'H7: 720[px] matches only - any enabled category<br>'."\n";

	if ($res eq 'H1'){ print '<INPUT TYPE=radio NAME="re" VALUE="H1" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="H1">'; }
	print 'H1: 1080[ipx] matches only - any enabled category<br>'."\n";

	if ($res eq 'DD'){ print '<INPUT TYPE=radio NAME="re" VALUE="DD" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="DD">'; }
	print 'DD: DVDr, DVD9, DVD5, BR2DVD (disk, not XviD or x264 and > 3GB, Newznab sites only)<br>'."\n";

	if ($res eq 'HS'){ print '<INPUT TYPE=radio NAME="re" VALUE="HS" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="HS">'; }
	print 'HS: Current Watch List season match - any quality, any enabled category<br>'."\n";

	if ($res eq 'AT'){ print '<INPUT TYPE=radio NAME="re" VALUE="AT" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="AT">'; }
	print 'AT: Anything matching title - any quality, any enabled category (new or old, Last ep ignored)<br>'."\n";

	print "	Use [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=P-WF\%20extras\">Skip Labels, Lang and Tv Hold</A>] settings to skip or hold listings with matching labels.<br>\n";
	print '</P>'."\n";
# 	if ($res){ 
# 		#$res =~ s!SR!SD!; # for R > D change
# 		#$res =~ s!HR!HD!;
# 		print "	<option selected value=\"$res\">$res</option>\n"; 
# 	}
# 	elsif ($select){ 
# 		$select =~ s!HD !HD+!;
# 		print "	<option selected value=\"$select\">$select</option>\n"; 
# 	}
# 	print "	</SELECT></P>\n\n";
	print "	<P>Priority - download queue priority (nzbget >= r443)<br>\n";
	print "	NEW: Set [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=P-General\">NzbgetRev</A>] if needed.<br>\n";
	print "	See also: [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=S-INCOMING\%20NZBS\">NzbDirInterval and NzbDirFileAge settings/notes</A>].<br>\n";
	#print "	<SELECT NAME=pr> <OPTION value=100>max</OPTION> <OPTION value=50>high</OPTION> <OPTION value=0>norm</OPTION> <OPTION value=-50>low</OPTION><OPTION value=-100>min</OPTION>\n";
	print "	<SELECT NAME=pr> <OPTION>max</OPTION> <OPTION>high</OPTION> <OPTION>norm</OPTION> <OPTION>low</OPTION><OPTION>min</OPTION>\n";
	if ($priority){ 
		print "	<option selected>$priority</option>\n"; 
	}
	else { print "	<option selected>norm</option>\n"; }
	print "	</SELECT></P>\n\n";
	
	print "	<P>Save name - default/blank = Show title (first title if more than one)<br>\n";
	print "	This is the name that will be used for directory and file names.<br>\n";
	if ($save_title){# and $save_title ne $title){ 
		print "	<INPUT TYPE=\"text\" SIZE=\"60\" NAME=\"st\" value=\"$save_title\"></P>\n"; 
	}
	else { print "	<INPUT TYPE=\"text\" SIZE=\"60\" NAME=\"st\" value=\"\"></P>\n"; }
	
	print "	<INPUT TYPE=\"hidden\" NAME=\"ca\" value=\"TV\">\n";
	if ($return){
		print "	<INPUT TYPE=\"hidden\" NAME=\"sc\" value=\"$return\">\n";
	}
	else {	print "	<INPUT TYPE=\"hidden\" NAME=\"sc\" value=\"\">\n"; }
	print "	<INPUT TYPE=\"hidden\" NAME=\"ot\" value=\"$title\">\n";
	print "	<input type=\"submit\" value=\"$type TV show\"></form>\n\n";
}

sub PrintMovieForm {
	# from listing example: nt=The%20Hurt%20Locker&la=2008&ca=VD&sc=Nzbsrus_Movies-XviD:1
	my ($type, $title, $label, $res, $priority, $save_title, $return) = @_ ;
	my $select;
	my $cat;
# 	if ($return =~ m!^([^_]+)_Movies-([^:]+):!){ #Nzbsrus_Movies-XviD:1
# 		my $site = $1;
# 		$select = $2;
# 		$cat = "Movies-$select";
# 		$site =~ s!Nzbsrus!NR!; 
# 		$site =~ s!Nzbsorg!NO!;
# 		$site =~ s!Nzbmatrix!NM!;
# 		$site =~ s!Nzbsu!NS!;
# 		$site =~ s!Dognzb!DN!;
# 		$site =~ s!Kerews!KW!;
# 		
# 		$select =~ s!XviD!$VAR{"$site\_SR_VD"}!;# NR_SR_VD
# 		$select =~ s!HD!$VAR{"$site\_HR_VD"}!;
# 	}
	print qq~
	<form action="$VAR{'WfCgi'}" method="$VAR{'FormMethod'}">
	<INPUT TYPE="hidden" NAME="do" VALUE="WL_$type">
	<P><B class="INFO">Video&nbsp;title</B> - can be a comma seperated list of IMDb, AKA, etc. names<br>
	<INPUT TYPE="text" SIZE="60" NAME="nt" VALUE="$title">
	</P>
	<P>Year - The script will compare this with the listing year (both needed for auto queue).<br>
	If the listing year is more than +/- 1 year different it will be skipped.<br>
	The year listed here will be added to save title if [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=P-Nzbs\">Year=yes</A>].<br>
	~;
	if ($label){ # year
		print "	<INPUT TYPE=\"text\" SIZE=\"10\" NAME=\"la\" value=\"$label\"></P>\n\n"; 
	}
	else { print "<INPUT TYPE=\"text\" SIZE=\"10\" NAME=\"la\" value=\"\"></P>\n\n"; }
# 	if ($select){ print "	<P>Which minimum quality level to watch for (default is configured level for $cat):<br>\n"; }
# 	else { print "	<P>Which minimum quality level to watch for:<br>\n"; }
# 	#print "	<P>Which minimum quality level to watch for (default is configured level)<br>\n";
# 	print "	BD = BLURAY, BD25, BD50 (disc, not XviD or x264, > 10GB)<br>\n";
# 	print "	DD = DVDR, DVD9, DVD5, BR2DVD (disk, not XviD or x264)<br>\n"; 
# 	print "	HD = (M)BluRay, B[RD]Rip, HDDVD, DVDRip (x264)<br>\n";
# 	print "	SD = DVDRip, B[RD]Rip, HDDVD (XviD) - same as DR (depreciated)<br>\n";
# 	print "	R5 = RC, R4, R5, R6<br>\n"; 
# 	print "	SC = Screener, SCRRip, DVDScr, VODRip, WEBRip, PPVRip, HDTV<br>\n";
# 	print "	TC = Telecine, TC<br>\n"; 
# 	print "	TS = Telesync, TS<br>\n"; 
# 	print "	CM = CAM, HDCAM<br>\n"; 
# 	print "	AL = Any Level<br>\n";

	print "	<P>Which minimum quality level to watch for:<br>\n";
	
	unless ($res){
		$res = $VAR{'VidRes'};
		unless ($res){
			$res = 'DR'; 
		}
	}
	
	if ($res eq 'BD'){ print '<INPUT TYPE=radio NAME="re" VALUE="BD" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="BD">' }
	print 'BD: BLURAY, BD25, BD50 (disc, not XviD or x264 and > 10GB, Newznab sites only)<br>'."\n";

	if ($res eq 'DD'){ print '<INPUT TYPE=radio NAME="re" VALUE="DD" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="DD">'; }
	print 'DD: DVDR, DVD9, DVD5, BR2DVD (disk, not XviD or x264 and > 3GB, Newznab sites only)<br>'."\n";

	if ($res eq 'HD'){ print '<INPUT TYPE=radio NAME="re" VALUE="HD" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="HD">'; }
	print 'HD: HD x264 - (M)BluRay, HDDVD, B[RD]Rip, DVDRip<br>'."\n";

	if ($res eq 'DR'){ print '<INPUT TYPE=radio NAME="re" VALUE="DR" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="DR">'; }
	print 'DR: SD XviD - DVDRip, B[RD]Rip<br>'."\n";

	if ($res eq 'R5'){ print '<INPUT TYPE=radio NAME="re" VALUE="R5" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="R5">'; }
	print 'R5: RC, R2, R4, R5, R6<br>'."\n";

	if ($res eq 'SC'){ print '<INPUT TYPE=radio NAME="re" VALUE="SC" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="SC">'; }
	print 'SC: Screener, SCRRip, DVDScr, VODRip, WEBRip, PPVRip, HDRip, HDTV<br>'."\n";

	if ($res eq 'TC'){ print '<INPUT TYPE=radio NAME="re" VALUE="TC" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="TC">'; }
	print 'TC: Telecine, TC<br>'."\n";

	if ($res eq 'TS'){ print '<INPUT TYPE=radio NAME="re" VALUE="TS" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="TS">'; }
	print 'TS: Telesync, TS<br>'."\n";

	if ($res eq 'CM'){ print '<INPUT TYPE=radio NAME="re" VALUE="CM" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="CM">'; }
	print 'CM: CAM, HDCAM<br>'."\n";

	if ($res eq 'AL'){ print '<INPUT TYPE=radio NAME="re" VALUE="AL" CHECKED>'; }
	else { print '<INPUT TYPE=radio NAME="re" VALUE="AL">'; }
	print 'AL: Any Title Year match found in enabled categories<br>'."\n";

	print "	Use [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=P-WF\%20extras\">Skip Labels, Lang and Vid Hold</A>] settings to skip or hold listings with matching labels.<br>\n";
	print "	Use [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=P-WF\%20extras\">HdRes</A>] to only download HD movie listings with 720p or 1080p labels.<br>\n";
	print '</P>'."\n";

# 	print "	<SELECT NAME=re><OPTION>BD</OPTION><OPTION>DD</OPTION><OPTION>HD</OPTION><OPTION>SD</OPTION><OPTION>R5</OPTION><OPTION>SC</OPTION><OPTION>TC</OPTION><OPTION>TS</OPTION><OPTION>CM</OPTION><OPTION>AL</OPTION>\n";
# 	if ($res){ print "<option selected value=\"$res\">$res</option>"; }
# 	elsif ($select){ 
# 		print "	<option selected value=\"$select\">$select</option>\n"; 
# 	}
# 	print "	</SELECT></P>\n\n";

	print "	<P>Priority - download queue priority (nzbget >= r443)<br>\n";
	print "	NEW: Set [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=P-General\">NzbgetRev</A>] if needed.<br>\n";
	print "	See also: [<A HREF=\"$VAR{'Protocol'}$VAR{'Host'}$VAR{'HomeUrl'}nzbgetweb/config.php?section=S-INCOMING\%20NZBS\">NzbDirInterval and NzbDirFileAge settings/notes</A>].<br>\n";
	#print "	<SELECT NAME=pr> <OPTION value=100>max</OPTION> <OPTION value=50>high</OPTION> <OPTION value=0>norm</OPTION> <OPTION value=-50>low</OPTION><OPTION value=-100>min</OPTION>\n";
	print "	<SELECT NAME=pr> <OPTION>max</OPTION> <OPTION>high</OPTION> <OPTION>norm</OPTION> <OPTION>low</OPTION><OPTION>min</OPTION>\n";
	if ($priority){ 
		print "	<option selected>$priority</option>\n"; 
	}
	else { print "	<option selected>norm</option>\n"; }
	print "	</SELECT></P>\n\n";
			
	print "	<P>Save name - default/blank = (first) Movie title<br>\n";
	if ($save_title){# and $save_title ne $title){ 
		print "	<INPUT TYPE=\"text\" SIZE=\"60\" NAME=\"st\" value=\"$save_title\"></P>\n"; 
	}
	else { print "	<INPUT TYPE=\"text\" SIZE=\"60\" NAME=\"st\" value=\"\"></P>\n"; }
	
	print "	<INPUT TYPE=\"hidden\" NAME=\"ca\" value=\"VIDEO\">\n";
	if ($return){
		print "	<INPUT TYPE=\"hidden\" NAME=\"sc\" value=\"$return\">\n";
	}
	else {	print "	<INPUT TYPE=\"hidden\" NAME=\"sc\" value=\"\">\n"; }
	print "	<INPUT TYPE=\"hidden\" NAME=\"ot\" value=\"$title\">\n";
	print "	<input type=\"submit\" value=\"$type video/movie\"></form>\n\n";
}

sub PrintTitleForm { # $site, nt, ot, sc (site_page:a_name)
	my ($site, $new_title, $old_title, $return) = @_ ; # old = orig, new = soon to be old listing title (ot)
	print qq~
	</font></pre><form action="$VAR{'WfCgi'}" method="$VAR{'FormMethod'}">
	<INPUT TYPE="hidden" NAME="do" VALUE="$site\_title_edit"> 
	~;
	if ($return =~ m!TV! and $new_title =~ m!s\d+e\d+!){
		print '<P>Note: The sNNeNN format should be left alone. <br>Queued nzbs will have [<A HREF="'.$VAR{'Protocol'}.$VAR{'Host'}.$VAR{'HomeUrl'}.'nzbgetweb/config.php?section=P-Nzbs">the format of your choice</A>].</P>';
	}
	print qq~
	<P>$old_title</P>
	<P><INPUT TYPE="text" SIZE="60" NAME="nt" value="$new_title"></P>
	<INPUT TYPE="hidden" NAME="ot" value="$new_title"> 
	<INPUT TYPE="hidden" NAME="sc" VALUE="$return"> 
	<input type="submit" value="Submit"></form>
	~;
}

sub TitleForm {# nt, ot, sc, an
	my ($site, $new_title, $old_title, $site_cat) = @_;
	$new_title =~ s!%([a-fA-F0-9]{2,2})!chr(hex($1))!eg;
	
	my $a_name;
	$site_cat =~ s!:(\d+)$!!;
	$a_name = $1;
	
	print "Content-type: text/html\n\n";
	$VAR{'HaveHeader'} = 1;
	my $related_links = &HtmRelated ('Edit Title', '');
	print &HtmHead ('Edit Title', '', "$VAR{'HtmlUrl'}/$site_cat.html#$a_name", "Return to $site_cat", $related_links);
	# currently the only call, could include it here
	&PrintTitleForm ($site, $new_title, $old_title, "$site_cat:$a_name");
	print &HtmFoot ("$VAR{'HtmlUrl'}/$site_cat.html#$a_name", "Return to $site_cat", '');
}

sub TitleEdit { # browse page title edit
	#my ($site, $new_title, $old_title, $site_cat) = @_;
	my ($site, $cgi) = @_;
	my $new_title = $cgi->param('nt');
	my $enc_new_title = $new_title;
	my $short_new_title = $new_title;
	
	$short_new_title =~ s!(.+?) (?:s|pt|e)?[\de-]+!$1!;
	$short_new_title =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg;
	$enc_new_title =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg;
	$new_title =~ s! !&nbsp;!g;# stupid explorer hack (green title)
	
	my $old_title = $cgi->param('ot');
	my $enc_old_title = $old_title;
	my $short_old_title = $old_title;
	
	$short_old_title =~ s!(.+?) (?:s|pt|e)?[\de-]+!$1!;
	$short_old_title =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg;
	$enc_old_title =~ s!([\W])!"%" . uc(sprintf("%2.2x",ord($1)))!eg;
	$old_title =~ s! !&nbsp;!g;# stupid explorer hack (green title)
	
	my $a_name;
	my $site_cat = $cgi->param('sc');
	$site_cat =~ s!:(\d+)$!!;
	$a_name = $1;
	open (WHTM, ">$VAR{'HtmlDir'}/$site_cat.html.tmp") or &Print ("  Couldn't open $site_cat.html.tmp, $! (120)", 1, 1);
	open (RHTM, "<$VAR{'HtmlDir'}/$site_cat.html") or &Print ("  Couldn't open $site_cat.html, $! (121)", 1, 1);
	while (<RHTM>){
		if (m!^<P><A NAME="$a_name"!i){ 
			my $line = $_;
			$line =~ s!(INFO|DEBUG)">$old_title</B!$1">$new_title</B!ig; # both w/ nbsp
			$line =~ s!nt=$enc_old_title&!nt=$enc_new_title&!ig; # both enc... doesn't match epless tvdb nt=
			# 3 2012 short title stuff for TVDb link update
			$line =~ s!nt=$short_old_title&!nt=$short_new_title&!ig; # both enc... matches epless nt= tvdb and others
			# only useful when there's an ep label/title messup, uses watchlist ep label (la=) for tvdb ep link
			if ($line =~ m!la=([^&]+)&!){ # 3 2012 added for TVDb ep update
				my $ep = $1;
				$line =~ s!ep=[^&]+&!ep=$ep&!g;
			}
			print WHTM $line;
		}
		else { print WHTM; }
	}
	close WHTM or warn $!;
	
	rename ("$VAR{'HtmlDir'}/$site_cat.html.tmp", "$VAR{'HtmlDir'}/$site_cat.html") or &Print ("  Couldn't rename $site_cat.html.tmp, $! (121)", 1, 1);
	close RHTM or warn $!;
	
	#print "Location: $VAR{'Protocol'}$VAR{'Host'}$VAR{'HtmlUrl'}/$site_cat.html#$a_name\n\n";
	print $cgi->redirect($VAR{'Protocol'}.$VAR{'Host'}.$VAR{'HtmlUrl'}.'/'.$site_cat.'.html#'.$a_name);
}

1;